package com.fiveGroup.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fiveGroup.pojo.Message;
import com.fiveGroup.pojo.User;
import com.fiveGroup.pojo.vo.DataVo;
import com.fiveGroup.service.MessageService;
import com.fiveGroup.service.UserService;
import com.fiveGroup.util.JwtUtil;
import com.fiveGroup.util.UserContextHolder;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Slf4j
@RestController
@RequestMapping("/api/message")
public class MessageController {

    @Autowired
    private MessageService messageService;

    @Autowired
    private UserService userService;

    @Autowired
    private JwtUtil jwtUtil;

    @PostMapping("/sendMessage")
    public DataVo sendMessage(@RequestBody Message message) {
        if (message.getContent() == null || message.getContent().trim().isEmpty()) {
            return DataVo.fail("消息不能为空");
        }

        // 设置默认值
        message.setCreatedAt(java.time.LocalDateTime.now());
        message.setReadStatus(0); // 0=未读

        // 获取当前登录用户ID作为发送者
        Long currentUserId = UserContextHolder.getUserId();
        // 设置发送者ID
        message.setSenderId(currentUserId);

        //设置默认 msgType
        if (message.getMsgType() == null || message.getMsgType().trim().isEmpty()) {
            message.setMsgType("text");  // 默认是文本
        }

        // 调用 service 保存（内部会触发 WebSocket 推送）
        boolean saved = messageService.save(message);

        if (saved) {
            return DataVo.success("消息发送成功");
        } else {
            return DataVo.fail("消息发送失败");
        }
    }

    @PostMapping("/upload/image")
    public DataVo uploadImage(@RequestParam("file") MultipartFile file) {
        try {
            String fileName = UUID.randomUUID().toString() + ".jpg";
            String filePath = "D:/uploads/" + fileName;

            Files.write(Paths.get(filePath), file.getBytes());

            // 构造访问路径（假设你配置了静态资源映射）
            String url = "/uploads/" + fileName;

            return DataVo.success(url);
        } catch (Exception e) {
            return DataVo.fail("上传失败：" + e.getMessage());
        }
    }

    /**
     * 获取与某用户的聊天记录
     */
    @GetMapping("/getChatHistory")
    public DataVo getChatHistory(@RequestParam(required = false) Integer otherUserId,
                                 HttpServletRequest request) {
        try {
            log.info("👥 开始获取聊天记录，对方用户ID: {}", otherUserId);

            // 获取当前登录用户ID
            Long currentUserIdLong = UserContextHolder.getUserId();
            if (currentUserIdLong == null) {
                log.warn("❌ 用户未登录");
                return DataVo.fail("用户未登录");
            }

            // 转换为Integer
            Integer currentUserId = currentUserIdLong.intValue();

            log.info("🔍 查询聊天记录: 当前用户={}, 对方用户={}", currentUserId, otherUserId);

            // 获取双向聊天记录
            List<Message> messages = messageService.getChatHistory(currentUserId, otherUserId);

            log.info("💬 查询到消息数量: {}", messages.size());
            messages.forEach(msg ->
                    log.debug("📨 消息详情: id={}, from={}, to={}, content={}",
                            msg.getId(), msg.getSenderId(), msg.getReceiverId(), msg.getContent())
            );

            return DataVo.success(messages);
        } catch (Exception e) {
            log.error("❌ 获取聊天记录失败: {}", e.getMessage(), e);
            return DataVo.fail("获取聊天记录失败: " + e.getMessage());
        }
    }

    /**
     * 标记为已读
     */
    @PutMapping("/read")
    public DataVo markAsRead(
            @RequestParam Integer senderId,
            @RequestParam Integer receiverId) {

        messageService.markAsRead(senderId, receiverId);
        return DataVo.success();
    }

    /**
     * 获取未读消息数
     */
    @GetMapping("/unread/count")
    public DataVo getUnreadCount(@RequestParam Integer receiverId) {
        Integer count = messageService.getUnreadCount(receiverId);
        return DataVo.success(count);
    }

    /**
     * 获取好友列表
     */
    @GetMapping("/friends/list")
    public DataVo getFriendList(HttpServletRequest request) {
        try {
            Long currentUserId = UserContextHolder.getUserId();
            Integer integerValue = Long.valueOf(currentUserId).intValue();
            List<Integer> friends = messageService.getFriends(integerValue);
            return DataVo.success(friends);
        } catch (Exception e) {
            System.err.println(e.getMessage());
            return DataVo.fail("获取好友列表失败：" + e.getMessage());
        }

    }

    /**
     * 根据好友列表的id，批量查出用户
     */
    @PostMapping("/listByIds")
    public DataVo listByIds(@RequestBody Map<String, List<Long>> request) {
        List<Long> ids = request.get("ids");
        if (ids == null || ids.isEmpty()) {
            return DataVo.success(Collections.emptyList());
        }

        // 查询用户，只查 id 和 username
        List<User> users = userService.list(new QueryWrapper<User>()
                .select("id", "username")
                .in("id", ids)
                .eq("status", 0)  // 只查正常用户
                .eq("is_delete", 0)
        );

        return DataVo.success(users);
    }

    /**
     * 获取当前登录用户的基本信息（id, username）
     * 用于 WebSocket 聊天场景
     */
    @GetMapping("/user/info")
    public DataVo getCurrentUserInfo(HttpServletRequest request) {
        try {
            // 1. 从 token 中解析 userId（复用现有 JwtUtil）
            String token = request.getHeader("Authorization");
            if (token != null && token.startsWith("Bearer ")) {
                token = token.substring(7);
            } else {
                token = request.getHeader("token"); // 兼容你同事的 header 名
            }

            if (token == null || token.isEmpty()) {
                return DataVo.fail(401, "未登录");
            }

            Claims claims = jwtUtil.extractAllClaims(token);
            Integer userId = (Integer) claims.get("userId");
            if (userId == null) {
                return DataVo.fail(401, "无效的 token");
            }

            // 2. 查询用户（只查 id 和 username）
            User user = userService.getById(userId);
            if (user == null || user.getStatus() != 0 || user.getIsDelete() == 1) {
                return DataVo.fail(404, "用户不存在或已被禁用");
            }

            // 3. 返回前端需要的字段
            return DataVo.success(Map.of(
                    "id", user.getId(),
                    "username", user.getUsername()
            ));

        } catch (Exception e) {
            log.error("获取用户信息失败:", e);
            return DataVo.fail(500, "服务器内部错误");
        }
    }
}
